package com.miracle9.game.server.message;

import com.miracle9.game.service.UserService;
import com.miracle9.game.service.XxFishService;
import com.miracle9.game.util.Encrypt;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class MinaServerHandler extends IoHandlerAdapter {
    private UserService userService;
    private XxFishService xxFishService;
    public static String key = "K1vsWt95wX7mXgoP";
    private Logger logger = Logger.getLogger(XsSocketHandler.class);

    public  MinaServerHandler(){

    }

    public  MinaServerHandler(UserService userService,XxFishService xxFishService){
        this.userService = userService;
        this.xxFishService = xxFishService;

    }

    public void sessionCreated(IoSession session) throws Exception {
        logger.info("h5，Address：" + session.getRemoteAddress());
        session.setAttribute("checkH5", 1);
    }

    public void sessionOpened(IoSession session) throws Exception {
    }

    public void sessionClosed(IoSession session) throws Exception {
        logger.info("h5，Address：" + session.getRemoteAddress());
    }

    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        logger.error(cause.getMessage());
        cause.printStackTrace();
    }


    public void messageReceived(IoSession session, Object m) throws Exception {
        if(m == null || StringUtils.isBlank(m.toString())){
            return;
        }
        logger.info("h5 req msg1111111111：" + m.toString());
        MinaBean minaBean = (MinaBean) m;
        if (minaBean.isWebAccept()) {
            MinaBean sendMessage = minaBean;
            sendMessage.setContent(WebSocketUtil.getSecWebSocketAccept(minaBean
                    .getContent()));
            session.write(sendMessage);
        } else {
            logger.info("h5 req msg2222222222：" + minaBean.getContent());
            try{
                String message = minaBean.getContent();
            if(message!=null && !message.startsWith("{")){
               // session.write(message);
                logger.info("no json");
                MinaBean res = new MinaBean();
                res.setContent("no json");
                session.write(res);
                return;
            }
            JSONObject jsonObject = null;
           try {
                 jsonObject = JSONObject.fromObject(message);
            }catch (Exception e){
                e.printStackTrace();
            }
            if(jsonObject!= null){
                //{"method":"gcuserService/login","time":1705056139062,"args":["qwe123","qwe123",0],"version":"1.2.14"}
                String method = jsonObject.getString("method");
                if(StringUtils.isNotBlank(method)){
                    if("gcuserService/login".equals(method)){
                        JSONObject data = jsonObject.getJSONObject("data");
                        Map<String, Object> result = userService.userLoginH5(data.getString("username"),data.getString("password"),"1.2.14",session)  ;
                        if(result!=null){
                            JSONObject res = new JSONObject();
                            res.put("method",method);
                            res.put("data",result) ;
                            sendMsg(session,res.toString());
                        }
                    }
                    if("gcuserService/register".equals(method)){
                        JSONObject data = jsonObject.getJSONObject("data");
                        Map<String, Object> result = userService.register(data,session)  ;
                        if(result!=null){
                            JSONObject res = new JSONObject();
                            res.put("method",method);
                            res.put("data",result) ;
                            sendMsg(session,res.toString());
                        }
                    }
                    if(!session.containsAttribute("loginkey")){
                        Map<String, Object> result = new HashMap<>();
                        result.put("success", Boolean.FALSE);
                        result.put("messageStatus", -4); // 未登录

                        JSONObject res = new JSONObject();
                        res.put("method","noLogin");
                        res.put("data",result) ;
                        sendMsg(session,res.toString());
                        return;
                    }
                    if("xxFishService/getDeskList".equals(method)){
                        String datam = jsonObject.getString("data");
                        String des = Encrypt.AESDecrypt(datam,key,false);
                        JSONObject data =JSONObject.fromObject(des);
                        Map<String, Object> result = xxFishService.getDeskList(data.getInt("userId"),data.getInt("gameType"),session)  ;
                        if(result!=null){
                            JSONObject res = new JSONObject();
                            res.put("method",method);
                            res.put("data",result) ;
                            sendMsg(session,res.toString());
                        }
                    }

                    if("xxFishService/enterRoom".equals(method)){
                        String datam = jsonObject.getString("data");
                        String des = Encrypt.AESDecrypt(datam,key,false);
                        JSONObject data =JSONObject.fromObject(des);
                        Map<String, Object> result = xxFishService.enterRoom(data.getInt("userId"),data.getInt("gameType"),data.getInt("deskId"),data.getInt("seatId"),session)  ;
                        if(result!=null){
                            JSONObject res = new JSONObject();
                            res.put("method",method);
                            res.put("data",result) ;
                            sendMsg(session,res.toString());
                        }
                    }

                    if("xxFishService/leaveRoom".equals(method)){
                        String datam = jsonObject.getString("data");
                        String des = Encrypt.AESDecrypt(datam,key,false);
                        JSONObject data =JSONObject.fromObject(des);
                        Map<String, Object> result = xxFishService.leaveRoom(data.getInt("userId"),data.getInt("gameType"),data.getInt("deskId"),data.getInt("seatId"),session)  ;
                        if(result!=null){
                            JSONObject res = new JSONObject();
                            res.put("method",method);
                            res.put("data",result) ;
                            sendMsg(session,res.toString());
                        }
                    }

                    if("xxFishService/operationKey".equals(method)){
                        String datam = jsonObject.getString("data");
                        String des = Encrypt.AESDecrypt(datam,key,false);
                        JSONObject data =JSONObject.fromObject(des);
                        Map<String, Object> result = xxFishService.operationKey(data.getInt("userId"),data.getInt("gameType"),data.getInt("amount"),data.getString("type"),data.getInt("deskId"),session)  ;
                        if(result!=null){
                            JSONObject res = new JSONObject();
                            res.put("method",method);
                            res.put("data",result) ;
                            sendMsg(session,res.toString());
                        }
                    }

                    if("xxFishService/leaveRoomQuit".equals(method)){
                        String datam = jsonObject.getString("data");
                        String des = Encrypt.AESDecrypt(datam,key,false);
                        JSONObject data =JSONObject.fromObject(des);
                        Map<String, Object> result = xxFishService.leaveRoomQuit(data.getInt("userId"),session)  ;
                        if(result!=null){
                            JSONObject res = new JSONObject();
                            res.put("method",method);
                            res.put("data",result) ;
                            sendMsg(session,res.toString());
                        }
                    }

                    if("xxFishService/checkUserRoom".equals(method)){
                        String datam = jsonObject.getString("data");
                        String des = Encrypt.AESDecrypt(datam,key,false);
                        JSONObject data =JSONObject.fromObject(des);
                        Map<String, Object> result = xxFishService.checkUserRoom(data.getInt("userId"),session)  ;
                        if(result!=null){
                            JSONObject res = new JSONObject();
                            res.put("method",method);
                            res.put("data",result) ;
                            sendMsg(session,res.toString());
                        }
                    }
                    if("heart".equals(method)){
                       session.write(m);
                    }
                }
            }
        }catch (Exception e){
            logger.error("h5 json error",e);
            session.close(true);
        }
        }



    }

    public  void sendMsg(IoSession session,String msg){
        try {
            MinaBean res = new MinaBean();
            res.setContent(Encrypt.AESUNURLEncrypt(msg,key));
            session.write(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
